<template>
  <div>
    <a-modal
      v-model:visible="visible"
      :footer="upgrade"
      bodyStyle=" padding:0;"
      title="设置"
      :width="600"
      @ok="handleOk"
    >
      <div class="flex">
        <div class="left">
          <div
            @click="itemClick(1)"
            :class="selected == 1 ? 'left-title1' : 'left-title'"
          >
            视频设置
          </div>
          <div
            @click="itemClick(2)"
            :class="selected == 2 ? 'left-title1' : 'left-title'"
          >
            音频设置
          </div>
          <div
            @click="itemClick(3)"
            :class="selected == 3 ? 'left-title1' : 'left-title'"
          >
            系统设置
          </div>

          <div
            @click="itemClick(4)"
            :class="selected == 4 ? 'left-title1' : 'left-title'"
          >
            服务端设置
          </div>
        </div>
        <div class="right">
          <div v-if="selected == 1">
            <div class="right-flex">
              <div class="title">
                <span class="red">*</span>
                <span> 来源：</span>
              </div>
              <!-- <select v-model="formState.source" @change="getSource">
                <option value="volvo">本地</option>
                <option value="saab">局域网</option>
              </select> -->

              <a-select
                @change="getSource"
                v-model="formState.source"
                :size="size"
                style="width: 200px"
                :options="signalList"
              ></a-select>
            </div>

            <div class="right-flex">
              <div class="title">
                <span class="red">*</span>
                <span>信号设备：</span>
              </div>
              <!-- <select v-model="formState.signal">
                <option value="volvo">Volvo</option>
                <option value="saab">Saab</option>
              </select> -->

              <a-select
                v-model="formState.signal"
                :size="size"
                style="width: 200px"
                :options="signalList1"
              ></a-select>

              <a-button
                v-if="formState.signal != ''"
                type="primary"
                style="margin-left: 20px"
                @click="getPreview"
                ghost
                >预览</a-button
              >
            </div>
            <div class="annotation">
              <div>注：</div>
              <div>1.需选定信号源后，才可以进行录制；</div>
              <div>
                2、若视频信号源选择为网络信号，则麦克风默认为选择默认,不可修改
              </div>
            </div>

            <div class="btn-flex">
              <a-button type="primary" :loading="loading" @click="getSet">确定</a-button>
              <a-button class="ml-10" @click="cancel"> 取消</a-button>
            </div>
          </div>

          <div v-if="selected == 2">
            <div class="right-flex">
              <div class="title">
                <span class="red">*</span>
                <span> 麦克风：</span>
              </div>
              <a-select
                v-model="formState.audio"
                :size="size"
                style="width: 200px"
                :options="audioList"
              ></a-select>
            </div>

            <div class="annotation">
              <div>
                注：若视频信号源选择为网络信号，则麦克风默认为选择默认,不可修改
              </div>
            </div>

            <div class="btn-flex">
              <a-button type="primary" :loading="loading" @click="getSet">确定</a-button>
              <a-button class="ml-10" @click="cancel"> 取消</a-button>
            </div>
          </div>

          <div v-if="selected == 3">
            <div class="set-flex">
              <div class="set-title">启动设置：</div>
              <div>
                <a-checkbox v-model="formState.startup"> 开机启动</a-checkbox>
                <div class="annotation">
                  注：若视频信号源选择为网络信号，则麦克风默认为选择默认,不可修改
                </div>

                <a-checkbox v-model="formState.minimization"
                  >开机启动后最小化窗口</a-checkbox
                >
                <div class="annotation">
                  注：勾选此项，软件在开机自动启动后，会 最小化窗口到任务栏。
                </div>
              </div>
            </div>

            <div class="set-flex">
              <div class="set-title mt-10">清除设置：</div>
              <div>
                <div class="mt-10">
                  清除
                  <a-input
                    class="day-input"
                    v-model="formState.clearDay"
                    placeholder="天数"
                  />
                  天之前的数据
                </div>
                <div class="annotation">
                  注：清除时间以当天0点为基准，根据设置的时间执行。数据包含录制完成的视频，主
                  题列表及上传列表的失败数据。
                  <!-- 例如：设置“清除5天前及更早的视频”，
                  清除时间在2025年3月13日，则系统将清除所有在2025年3月8日00:00之前
                  录制完成的视频文件 -->
                </div>
              </div>
            </div>

            <div class="btn-flex">
              <a-button type="primary" :loading="loading" @click="getSet">确定</a-button>
              <a-button class="ml-10" @click="cancel"> 取消</a-button>
            </div>
          </div>

          <div v-if="selected == 4">
            <div class="right-flex">
              <div class="title">
                <span class="red">*</span>
                <span> 网络域名：</span>
              </div>

              <a-input v-model="formState.network" placeholder="网络域名" />

              <!-- <select v-model="formState.region">
                <option value="volvo">Volvo</option>
                <option value="saab">Saab</option>
              </select> -->
            </div>

            <div class="right-flex">
              <div class="title">
                <span class="red">*</span>
                <span>端口号：</span>
              </div>
              <a-input v-model="formState.port" placeholder="端口号" />

              <!-- <select v-model="formState.region">
                <option value="volvo">Volvo</option>
                <option value="saab">Saab</option>
              </select> -->
            </div>

            <div class="btn-flex">
              <a-button type="primary" :loading="loading" @click="getSet">确定</a-button>
              <a-button class="ml-10" @click="cancel"> 取消</a-button>
            </div>
          </div>
        </div>
      </div>
    </a-modal>

    <a-modal
      v-model:visible="preview"
      bodyStyle=" padding:0;"
      title="预览"
      :width="600"
    >
      <!-- 网络摄像头 -->
      <video
        id="video"
        v-if="formState.source == '网络摄像头'"
        controls
        width="600"
        height="400"
      ></video>

      <!-- 本地摄像头 -->
      <video
        id="videoElement"
        v-if="formState.source == '本地摄像头'"
        ref="videoElement"
        width="100vw"
        height="50%"
        autoplay
      ></video>
    </a-modal>
  </div>
</template>

<script>
// import videojs from "video.js";
// import "video.js/dist/video-js.css";
// import "videojs-contrib-hls"; // 如果需要HLS支持，可以添加此插件
import "../utils/hls";
import axios from "axios";
import { getByMacAddress, updateClearNumber } from "@/api/course.js";

export default {
  data() {
    return {
      visible: false,
      preview: false,
      upgrade: null,
      selected: 1,
      formState: {
        source: "", //来源
        signal: "", //摄像头
        audio: "", // 音频
        startup: false, // 开机是否启动
        minimization: false, // 开机最小化
        clearDay: 5, // 清除天数
        network: "", // 网络域名
        port: "", // 端口号
      },
      signalList: ["本地摄像头", "网络摄像头"],
      signalList1: ["一号摄像头"],
      audioList: [],
      player: null,
      businessId: "",
      loading:false,
    };
  },
  created() {
    let that = this;
    navigator.mediaDevices
      .getUserMedia({ audio: true })
      .then(function (stream) {
        // 成功获取媒体流
        const audioTracks = stream.getAudioTracks();
        if (audioTracks.length > 0) {
          console.log("麦克风设备信息:", audioTracks[0].label); // 显示麦克风标签名
          that.audioList = [];
          that.audioList.push({
            value: audioTracks[0].id,
            label: audioTracks[0].label,
          });
        }
      })
      .catch(function (error) {
        // 错误处理
        console.error("获取麦克风失败:", error);
      });
  },
  mounted() {},
  beforeDestroy() {
    if (this.player) {
      this.player.dispose(); // 清理播放器实例以避免内存泄漏
    }
  },
  methods: {
    async getSet() {
      if (!this.formState.network || !this.formState.port) {
  this.$message.error("请先填写域名或端口号！");
  this.itemClick(4)
  return;
}else{
   const port = parseInt(this.formState.port, 10);
  if (isNaN(port) || port < 1 || port > 65535) {
    this.$message.error("端口号必须是1~65535之间的正整数！");
    return;
  }
}
      if (!this.formState.signal||!this.formState.source) {
   this.$message.error("请先配置视频设备！");
   this.itemClick(1)
  return;
}

if (!this.formState.audio) {
   this.$message.error("请先配置音频设备！");
   this.itemClick(2)
  return;
}
if (!this.formState.clearDay) {
  this.$message.error("请先填写清除天数！");
  this.itemClick(3)
  return;
}else{
   const clearDay = parseInt(this.formState.clearDay, 10);
  if (isNaN(clearDay) || clearDay <= 0 || clearDay > 999) {
    this.$message.error("清除天数必须是正整数，最多3位数！");
    return;
  }
}
      // this.visible = false;
      this.loading = true;
      localStorage.setItem("set", JSON.stringify(this.formState));
      if (this.formState.clearDay) {
        const res = await updateClearNumber({
          macAddress: localStorage.getItem("macAddress"),
          clearNumber: this.formState.clearDay,
        }).then((res)=>{
        this.loading = false;
        this.$message.success("设置成功！");
        }).catch((error)=>{
          this.loading = false;
          this.$message.error(error.message);
        })
      }
    },
    async getInfo() {
      try {
        const res = await getByMacAddress({
          macAddress: localStorage.getItem("macAddress"),
        });
        if (res.data) {
          this.formState.clearDay = res.data.clearNumber;
        }
        console.log(res);
      } catch (error) {
        console.log(error, "错误信息");
      }
    },
    getSource(e) {
      this.formState.signal = "";
      if (this.formState.source == "本地摄像头") {
        this.signalList1 = ["USB摄像头"];
      } else {
        this.signalList1 = ["一号摄像头"];
      }
    },
    show() {
      this.visible = true;
      if (localStorage.getItem("set")) {
        this.formState = JSON.parse(localStorage.getItem("set"));
        this.formState.audio = this.audioList[0].value;
      }
      this.getInfo();
    },

    getPreview() {
      this.preview = true;

      if (this.formState.source == "网络摄像头") {
        const video = document.getElementById("video");

        this.rtspUrl = this.formState.network + this.formState.port;
        this.businessId = new Date().getTime();

        try {
          const response = axios.get(
            `http://192.168.1.117:8080/stream/startRstpConvert?rtspUrl=${this.rtspUrl}&fileName=${this.businessId}`
          ); // 替换为你的API URL
        } catch (error) {
          console.error("There was an error!", error);
        }

        //播放录制的视频
        if (Hls.isSupported()) {
          let url = `http://192.168.1.117:8080/stream/play/${this.businessId}/hlsStream.m3u8`;
          const hls = new Hls();
          hls.loadSource(url);
          hls.attachMedia(video);
          hls.on(Hls.Events.MANIFEST_PARSED, () => {
            // 直接跳转到末尾（最新时刻）
            video.currentTime = video.duration;
          });
        } else if (video.canPlayType("application/vnd.apple.mpegurl")) {
          video.src = url;
          video.addEventListener("loadedmetadata", () => video.play());
        }
      }

      if (this.formState.source == "本地摄像头") {
        this.takePhotoUpload();
      }

      // const that = this;
      // this.timers = setTimeout(() => {
      //   that.$nextTick(() => {
      //     this.preview = true;

      //     this.player = videojs(this.$refs.videoPlayer, {
      //       autoplay: true, // 如果需要自动播放的话
      //       controls: true, // 显示控制栏
      //       fluid: true, // 保持宽高比
      //       sources: [
      //         {
      //           // 这里可以添加你的RTSP源，但通常需要通过其他方式转换为HLS等格式
      //           src: "rtsp://127.0.0.1:554/easy.mp4", // 示例URL，实际应替换为你的RTSP流URL或转换后的HLS URL
      //           // type: "video/mp4", // 确保这里的type正确反映了你的流类型（例如：application/x-mpegURL对于HLS）
      //           type: "application/x-mpegURL", // 确保这里的type正确反映了你的流类型（例如：application/x-mpegURL对于HLS）
      //         },
      //       ],
      //       techOrder: ["html5", "hls"], // 使用HTML5播放器技术
      //       html5: {
      //         vhs: {
      //           overrideNative: true,
      //         },
      //         nativeVideoTracks: false,
      //         nativeAudioTracks: false,
      //         nativeTextTracks: false,
      //       },
      //     });
      //   });
      // }, 1000);
    },

    async takePhotoUpload() {
      console.log("===========进入摄像头函数");
      let device = ""; // 所选择的摄像头 deviceId
      // 加入音频（ 直接 audio: true, video: true 无效 所以要单独写 而后再另外加入音频）
      let audioTracks = await navigator.mediaDevices
        .getUserMedia({ audio: true, video: false })
        .then((mediaStream) => mediaStream.getAudioTracks()[0]);
      // 此处开启摄像头
      let stream = navigator.mediaDevices
        .enumerateDevices()
        .then((devices) => {
          //多个摄像头设备时，该处根据设备id判断具体使用哪个摄像头设备
          for (let i in devices) {
            if (devices[i].kind == "videoinput") {
              device = devices[i];
              break;
            }
          }
        })
        .then(async () => {
          navigator.mediaDevices
            .getUserMedia({
              audio: false,
              video: {
                sourceId: device.deviceId, // 把对应的 摄像头ID 放到这里
                // width: 500,
                height: 600, // 宽高可根据个人不同设计
                //如果拍照不清晰，考虑加入以下参数，但考虑下摄像头的高度和画布的高度
                width: { min: 1000, ideal: 1000, max: 3264 },
                // height:{min: 1080, ideal: 1080, max: 2488}
              },
            })
            .then(async (success) => {
              this.startType = 0;
              sessionStorage.setItem("startType", this.startType);
              success.addTrack(audioTracks); //加入音频
              this.$refs["videoElement"].srcObject = success; //测试阶段通过播放来判断是否成功调取成功
              this.$refs["videoElement"].play();
              //   this.createRecorder(success);
              this.stream = success;
              return;
            });

          // .catch((error) => {
          //   console.error("摄像头开启失败，请检查摄像头是否可用！");
          // });
        });
    },

    async startCamera() {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({
          video: true,
        });

        this.$refs.videoElement.srcObject = stream;
      } catch (error) {
        console.error("Error accessing the camera", error);
      }
    },
    async requestCameraAccess() {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({
          video: true,
        }); // 请求视频流
        const videoElement = document.getElementById("videoElement"); // 获取视频元素
        videoElement.srcObject = stream; // 将视频流绑定到视频元素上
        this.stream = stream;
        videoElement.play(); // 开始播放视频流
      } catch (error) {
        console.error("Error accessing the camera", error);
      }
    },

    itemClick(type) {
      this.selected = type;
    },
    handleOk() {
      this.visible = false;
    },
    cancel() {
      this.visible = false;
    },
    onSubmit() {},
    resetForm() {},
  },
};
</script>
<style lang="less" scoped>
.flex {
  display: flex;
}
.left {
  width: 100px;
  height: 100%;
  margin-top: 20px;
  margin-left: 20px;
  background: #f9f9f9;
}
.arco-modal-body {
  padding: 0 !important;
}
.left-title {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100px;
  height: 30px;
  cursor: pointer;
}
.left-title1 {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100px;
  height: 30px;
  color: #237dff;
  background: #e8edff;
  cursor: pointer;
}
.right {
  margin: 10px;
  height: 500px;
}
.right-flex {
  display: flex;
  align-items: center;
  margin-top: 20px;
  margin-bottom: 20px;
  .red {
    color: red;
  }
  select {
    width: 250px;
    height: 30px;
  }
}
.title {
  width: 120px;
  text-align: right;
}
.annotation {
  color: #b7b7b7;
  font-size: 10px;
  margin-left: 20px;
  margin-top: 5px;
}
.btn-flex {
  display: flex;
  justify-content: center;
  margin-top: 40%;
}
.ml-10 {
  margin-left: 10px;
}
.set-flex {
  display: flex;
  margin-top: 20px;
}
.set-title {
  min-width: 80px;
}
.day-input {
  width: 60px;
}

#videoElement {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.mt-10 {
  margin-top: 10px;
}
</style>
